<!-- 刷题与闯关 任务 -->
<template>
    <div>
        <div aria-label="A complete example of page header" class="pageview">
            <el-skeleton :rows="15" animated :loading="gujiaping">
                <div style="margin-bottom: 10px;margin-top:10px;">
                    <el-descriptions title="新增任务" direction="vertical" :column="2" border>
                        <el-descriptions-item label="任务名称">
                            <el-input placeholder="请输入试卷名" v-model="tname" />
                        </el-descriptions-item>
                        <el-descriptions-item label="任务难度">
                            <el-rate :min="1" :max="10" v-model="tlv" />
                        </el-descriptions-item>
                        <el-descriptions-item label="任务标签">
                            <el-checkbox v-for="(item, index) in checkList" :key="index" :label="item" v-model="tlabels">
                                {{ item }}
                            </el-checkbox>
                        </el-descriptions-item>
                        <el-descriptions-item label="任务描述">
                            <el-input :rows="2" type="textarea" v-model="texplain" />
                        </el-descriptions-item>
                    </el-descriptions>
                </div>
                <div class="title">
                    <p>任务详情</p>
                </div>
                <div style="text-align:right; margin-top: -30px;">
                    <el-button type="danger" size="default" @click="addTab(editableTabsValue)" plain>
                        新增子关卡
                    </el-button>
                </div>
                <div class="tabscss">
                    <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" :closable="ar"
                        @tab-remove="removeTab">
                        <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
                            <el-descriptions title="新增任务" direction="vertical" :column="2" border>
                                <el-descriptions-item label="是否固定题目">
                                    <el-radio-group v-model="item.disFixed" class="ml-4">
                                        <el-radio label="1" size="large">YES,我要求固定试题</el-radio>
                                        <el-radio label="0" size="large">NO,我要求随机试题</el-radio>
                                    </el-radio-group>
                                </el-descriptions-item>
                                <el-descriptions-item label="达标题目数(最少10道题)">
                                    <el-input-number :disabled="item.disFixed == 1 ? true : false"
                                        v-model="item.dlimitCount" :min="50" style="width: 100%;" />
                                </el-descriptions-item>
                                <el-descriptions-item label="难度区间(1-10)">
                                    <el-slider :disabled="item.disFixed == 1 ? true : false" range show-stops
                                        v-model="item.nxlv" :min="1" :max="10" />
                                </el-descriptions-item>
                                <el-descriptions-item label="达标正确率(最少为20%)">
                                    <el-input-number v-model="item.drightPercent" :min="20" style="width: 100%;" />
                                </el-descriptions-item>
                                <el-descriptions-item label="任务试题(最少为10道题)" v-if="item.disFixed == 1">
                                    <div>
                                        <el-button type="primary" size="small" @click="xuanze(item.title)">选择试题</el-button>
                                        <el-tag>第二次选择试题时会覆盖掉原有试题！</el-tag>
                                        <el-table :data="item.tableData" style="width: 100%">
                                            <el-table-column type="index" label="序号" width="60">
                                            </el-table-column>
                                            <el-table-column prop="content" label="题干" width="180" show-overflow-tooltip>
                                            </el-table-column>
                                            <el-table-column prop="lv" label="难度">
                                            </el-table-column>
                                            <el-table-column label="标签">
                                                <template #default="scope">
                                                    <el-tag :key="item.id" v-for="item in scope.row.labels.split(',')">
                                                        {{ item }}
                                                    </el-tag>
                                                </template>
                                            </el-table-column>
                                            <el-table-column prop="author" label="作者">
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </el-descriptions-item>
                                <el-descriptions-item label="题库约束(最多可选5个题库)" v-if="item.disFixed == 0">
                                    <el-checkbox-group @change="changes" v-model="item.checked">
                                        <label style="margin-left: 30px;" v-for="(item2, index) in item.Question"
                                            :key="index">
                                            <el-checkbox :label="item2.name" />
                                        </label>
                                    </el-checkbox-group>
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions direction="vertical" :column="1" border>
                                <el-descriptions-item label="操作">
                                    <el-button type="primary" :disabled="tname == '' || tlv == '' || tlabels == ''"
                                        @click="taskadds">确认新增</el-button>
                                </el-descriptions-item>
                            </el-descriptions>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </el-skeleton>
        </div>
        <taskdialogVisible v-if="dialogVisibleA" :data="editableTabs" :dialogVisible="dialogVisibleA" @close="changeVi"
            @datas="zzzzzz" :destroy-on-close="true">
        </taskdialogVisible>
    </div>
</template>
<script lang="ts">

import { defineComponent, getCurrentInstance, onMounted, reactive, toRefs } from 'vue'
import router from '../../../router';
import { useRoute } from 'vue-router';
import { AddTask } from '../../../api/practice/task/index';
import { GetLabels, GetQuestionBanks } from "../../../api/question/question";
import taskdialogVisible from '../../../views/practice/task/taskdialogVisible.vue';
import { ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus'
export default defineComponent({
    components: { taskdialogVisible },
    setup() {
        const { ctx } = getCurrentInstance() as any;
        const route = useRoute();
        onMounted(() => {
            event.GetLabel();
            event.GetQuestionBanks();
        })
        const shujudata = reactive({
            itemlist: [],
            tname: '',//任务名称
            tlv: '1',//任务难度
            tlabels: [],//任务标签
            texplain: '',//任务描述
            top: 'top',
            checkList: [],//标签列表
            tableData: [],//--1
            Question: [],//获取题库列表
            gujiaping: true,
            ar: true,
            editableTabsValue: 1,//默认选中tabs
            //默认有一个tabs
            editableTabs: ([
                {
                    title: '任务1',
                    name: 1,
                    disFixed: "0",//是否固定题目
                    dlimitCount: 50,//达标题目数
                    nxlv: [0, 10],//难度区间
                    drightPercent: 50,//达标正确率
                    tableData: [],//任务试题
                    Question: [],//获取题库列表
                    checked: [],//题库约束
                },
            ]),
            tabIndex: 2,
            dialogVisibleA: false,
        })

        const event = {
            changes(val: any) {
                console.log(shujudata.editableTabs)
            },
            zzzzzz(val: any) {
                //shujudata.tableData = val;
                shujudata.editableTabs.forEach((item: any) => {
                    console.log("///////////", item)
                    //当item.title==缓存title--将值传给item.tableData--再传入shujudata.editableTabs
                    if (item.title == sessionStorage.getItem("title")) {
                        item.tableData = val;
                    }
                });
                console.log("--------shujudata.tableData--------", shujudata.editableTabs)
            },
            //对话框
            xuanze(title: any) {
                console.log("选择的对话框title", title)
                sessionStorage.setItem("title", title)//缓存title
                shujudata.dialogVisibleA = true
            },
            changeVi() {
                shujudata.dialogVisibleA = false//关闭销毁dialog
            },
            //确认新增
            taskadds() {
                var lables: any = [];
                //拿题库约束的id
                shujudata.editableTabs.forEach((item: any) => {
                    var labs: any = [];
                    if (item.checked.length > 0) {
                        item.checked.forEach((item2: any) => {
                            if (item.Question.find((d: any) => d.name == item2) != undefined) {
                                labs.push(item.Question.find((d: any) => d.name == item2).id)
                            }
                        });
                    }
                    console.log("123456+labs", labs)
                    lables.push({
                        title: item.title,
                        lables: labs
                    })
                });

                var qids1: any = [];
                shujudata.editableTabs.forEach((item: any) => {
                    var ids: any[] = [];
                    item.tableData.forEach((item2: any) => {
                        ids.push(item2.id)
                    });
                    qids1.push({
                        title: item.title,
                        ids: ids
                    })
                });
                console.log(">>>>>>>>>>>>>>>>>>>>>.", qids1)
                //数组需要循环拿值
                var arr: any = [];
                shujudata.editableTabs.forEach((element: any) => {
                    arr.push({
                        isFixed: element.disFixed,
                        limitCount: element.dlimitCount,
                        lvRange: element.nxlv,
                        maxLv: element.nxlv[1],
                        minLv: element.nxlv[0],
                        name: element.title,
                        qbids: lables.find((d: any) => d.title == element.title) != undefined ? lables.find((d: any) => d.title == element.title).lables : [],
                        qids: qids1.find((d: any) => d.title == element.title) != undefined ? qids1.find((d: any) => d.title == element.title).ids : [],
                        rightPercent: element.drightPercent,
                        selectedQuestions: []//element.Question,//加了一堆
                    })
                });
                ElMessageBox.confirm('你确认要新增吗?', '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                }).then(() => {
                    AddTask({
                        name: shujudata.tname,
                        lv: shujudata.tlv,
                        explain: shujudata.texplain,
                        labels: shujudata.tlabels,
                        details: arr
                    }).then((res: any) => {
                        if (res.result === 0) {
                            ElMessage({
                                message: '添加成功!',
                                type: 'success',
                            })
                            router.push("/practice/task");
                        } else {
                            ElMessage({
                                message: '添加失败!',
                                type: 'error',
                            })
                        }
                    })
                }).catch(() => {
                    ElMessage({
                        message: '操作已取消',
                        type: 'info',
                    })
                });
            },
            //新增一个页面
            addTab(editableTabsValue: number) {
                if (shujudata.editableTabs.length < 10) {
                    const newTabName = shujudata.tabIndex++
                    console.log('应该选第', newTabName, '个界面')
                    console.log("有", shujudata.editableTabs.length + 1, "界面")
                    var lengs = shujudata.editableTabs.length + 1
                    shujudata.editableTabs.push({
                        title: '任务' + lengs,//名称
                        name: newTabName,//选择第几个
                        disFixed: "0",//是否固定题目
                        dlimitCount: 50,//达标题目数
                        nxlv: [1, 10],//难度区间
                        drightPercent: 50,//达标正确率
                        Question: shujudata.Question,//题库约束数据
                        //---------------------不能分开绑定数据
                        tableData: [],//任务试题
                        checked: [],//题库约束
                    })
                    shujudata.editableTabsValue = newTabName//新增选中的页面
                } else {
                    ElMessage({
                        message: '当前最多允许10个子任务',
                        type: 'error',
                    })
                }
            },
            //删除一个页面
            removeTab(targetName: any) {
                if (shujudata.editableTabs.length > 1) {
                    const tabs = shujudata.editableTabs
                    let activeName = shujudata.editableTabsValue
                    if (activeName === targetName) {
                        console.log("删除的页面activeName", activeName)
                        console.log("删除的页面targetName", targetName)
                        tabs.forEach((tab: any, index: any) => {
                            if (tab.name === targetName) {
                                console.log("tab.name", tab.name)
                                console.log("targetName", targetName)
                                const nextTab = tabs[index + 1] || tabs[index - 1]
                                if (nextTab) {
                                    console.log("nextTab", nextTab)
                                    activeName = nextTab.name
                                    console.log("选中", activeName, "第个页面")
                                }
                            }
                        })
                    }
                    shujudata.editableTabsValue = activeName
                    shujudata.editableTabs = tabs.filter((tab: any) => tab.name !== targetName)

                    // var wws = shujudata.editableTabs;
                    // shujudata.editableTabs = [];
                    // var lengs = 0;
                    // wws.forEach((item: any, index: any) => {
                    //     lengs += 1;
                    //     shujudata.editableTabs.push({
                    //         title: '任务' + lengs,
                    //         name: lengs,
                    //         disFixed: item.disFixed,//是否固定题目
                    //         dlimitCount: item.dlimitCount,//达标题目数
                    //         nxlv: item.nxlv,//难度区间
                    //         drightPercent: item.drightPercent,//达标正确率
                    //         Question: shujudata.Question,//题库约束数据
                    //         //---------------------不能分开绑定数据
                    //         dlabels: [],//题库约束
                    //         tableData: [],//任务试题
                    //     })
                    // });
                } else {
                    ElMessage({
                        message: '你无法移除最后一个子任务',
                        type: 'error',
                    })
                }
            },
            //获取题库列表
            GetQuestionBanks() {
                GetQuestionBanks({
                    page: 1,
                    limit: 99,
                    isPublish: 1
                }).then((res: any) => {
                    shujudata.Question = res.data.data;
                    shujudata.editableTabs[0].Question = res.data.data;//赋给第一个tabs的复选框值
                    shujudata.gujiaping = false
                })
            },
            // 获取标签
            GetLabel() {
                GetLabels({}).then((res: any) => {
                    if (res.result == 0) {
                        shujudata.checkList = res.data
                        shujudata.gujiaping = false
                    }
                })
            },
        }
        return {
            ...toRefs(shujudata),
            ...event,
        }
    },
})
</script>

<style scoped>
.pageview {
    min-width: 720px;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    user-select: none;
}

.page {
    padding-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.title {
    background-color: rgb(199, 206, 216);
    height: 30px;
    line-height: 30px;
    color: #fff;
    font-weight: 700;
    padding-left: 15px;
    width: 110px;
    border-top-right-radius: 15px;
    border-bottom-right-radius: 15px;
    margin-left: -30px;
}

.tabscss {
    margin-top: 20px;
    padding: 10px;
    box-shadow: 0 2px 12px #0000001a;
    border-radius: 5px;
}
</style>